var ctx = localStorage.getItem("ctx");
var table = '';
$(function() {
	
	juicer.set({
	    'tag::operationOpen': '-~',
	    'tag::operationClose': '+',
	    'tag::interpolateOpen': '#-',
	    'tag::interpolateClose': '+',
	    'tag::noneencodeOpen': '##-',
	    'tag::noneencodeClose': '+',
	    'tag::commentOpen': '-*',
	    'tag::commentClose': '+'
	});
	
	
	
	
	
	
	var newsysUserId = '';
	
	//获取table
	userTable('','');
	
	
	
	
	//查询
	$(".btn-search").on('click', function() {
		
		var organizationType = $(".orginizationSelect").find("option:selected").attr("value");
		var companyId = $(".companySelect").find("option:selected").attr("value");
		
		if(organizationType == 0) {
			companyId = null;
		}
		table.destroy();
		//查询获取table
		userTable(companyId,organizationType);
		
	});
	
	//添加和编辑获取角色列表以及机构类型初始化
	editgetRoleList();
	getRoleList();
	getCompany('0');
	addgetCompany('1');
	//根据机构类型获取公司
	$(".orginizationSelect").on("change", function() {
		var organizationType = $(this).attr("value");
		getCompany(organizationType);
	});
	$(".addorginizationSelect").on("change", function() {
		var organizationType = $(this).attr("value");
		addgetCompany(organizationType);
	});
	$(".editorginizationSelect").on("change", function() {
		var organizationType = $(this).attr("value");
		editgetCompany(organizationType);
	});
	
	//查看详情
	$(document).on('click', '.btn-detail', function() {
		var data = table.row( $(this).parents('tr') ).data();
		console.log(data);
		$(".loginName").html(data.loginName);
		$(".trueName").html(data.trueName);
		$(".roleName").html(data.roleName);
		$(".organizationName").html(data.organizationName);
		$(".createTime").html(data.createTime);
		$(".cityName").html(data.cityName);
		$(".updateTime").html(data.updateTime);
		var userStatus = data.userStatus;
		if(userStatus == 0) {
			$(".userStatus").html("不可登录");
		}
		else if(userStatus == 1) {
			$(".userStatus").html("可登录");
		}
		else {
			$(".userStatus").html("未知状态");
		}
		$('#myModalDetail').modal('show');
	});
	//编辑用户详情
	$(document).on('click', '.btn-edit', function() {
		var data = table.row( $(this).parents('tr') ).data();
		newsysUserId = data.sysUserId;
		console.log(data);
		$(".editloginName input").val(data.loginName);
		$(".edittrueName input").val(data.trueName);
		$(".edittelphone").val(data.phone);
		$(".editbeizhu").val(data.remarks);
		$(".editbianhao").val(data.sysUserId);
		$(".editroleSelect").find("option[value="+data.sysRoleId+"]").attr("selected", true);
		$(".editorginizationSelect").find("option[value="+data.organizationType+"]").attr("selected", true);
		$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/organization/listByType',
    		dataType: 'json',
    		data: {
    			organizationType: '-1'
    		},
    		success: function(data1) {
    			console.log(data1);
    			var company = {};
    			company.list = data1;
    			var companyTpl = document.getElementById("editcompanySelectTpl").innerHTML;
    			var companyhtml = juicer(companyTpl, company);
    			$(".editcompanySelect").html(companyhtml);
    			$(".editcompanySelect").find("option[value="+data.organizationId+"]").attr("selected", true);
    		}
    	});
		$(".edituserStatus").find("input[value="+data.userStatus+"]").attr("checked", true);
		$('#myModalEdit').modal('show');
	});
	
	$("#edituserform").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	edittrueName: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            editloginName: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            edittelphone: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
            		regexp: {
            			regexp: /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/,
            			message: '请输入正确手机号码'
            		}
                }
            }
        }
	});
	
	//确认保存用户修改
	$(".save-edit-btn").on("click", function() {
		saveuseredit();
	});
	
	//添加用户
	$(".btn-add").on("click", function(){
		$('#myModalAdd').modal('show');
	});
	
	$("#adduserform").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	addpassword: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^[0-9A-Za-z]{6,20}$/,
                    	message: '6-20位字母和数字组成'
                    }
                }
            },
            addtrueName: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            addloginname: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            addtelphone: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
            		regexp: {
            			regexp: /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/,
            			message: '请输入正确手机号码'
            		}
                }
            }
        }
	});
	
	//确认添加用户
	$(".add-confirm-btn").on("click", function() {
		
		confirmadduser();
		
	});
	
	//删除
	$(document).on('click', '.btn-delete', function() {
		var data = table.row( $(this).parents('tr') ).data();
		console.log(data);
		$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/user/del',
    		dataType: 'json',
    		data: {
    			sysUserId: data.sysUserId
    		},
    		success: function(data) {
    			if(data == true) {
    				alert("删除成功");
    				location.replace(location.href);
    			}
    			else {
    				alert("删除失败");
    			}
    		}
    	});
	});
	
	//禁用
	$(document).on('click', '.btn-forbid', function() {
		var data = table.row( $(this).parents('tr') ).data();
		console.log(data);
		//1:启用 0:禁用
		if(data.userStatus == 1) {
			statusForbidOrNot(0, data.sysUserId);
		}
		else {
			statusForbidOrNot(1, data.sysUserId);
		}
	});
	
	//修改密码模态框显示
	$(document).on('click', '.btn-editpas', function() {
		var data = table.row( $(this).parents('tr') ).data();
		newsysUserId = data.sysUserId;
		console.log(data);
		$("#myModaleditpass").modal('show');
	});
	$("#edituserpswform").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	newpassword: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^[0-9A-Za-z]{6,20}$/,
                    	message: '6-20位字母和数字组成'
                    }
                }
            },
            newpasswordagain: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    identical: {
                    	field: 'newpassword',
                    	message: '两次密码不一致'
                    }
                }
            }
        }
	});
	//确认修改密码
	$(".btn-confirm-edit-password").on('click', function() {
		
		var newpassword = $('.newpassword').val();
		var newpasswordagain = $('.newpasswordagain').val();
		confirmeditpassword(newpassword);
		
	});
	
	//根据机构类型获取公司
	function getCompany(organizationType) {
    	$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/organization/listByType',
    		dataType: 'json',
    		data: {
    			organizationType: organizationType
    		},
    		success: function(data) {
    			console.log(data);
    			var company = {};
    			company.list = data;
    			var companyTpl = document.getElementById("companySelectTpl").innerHTML;
    			var option = "<option value=''>请选择</option>";
    			var companyhtml = juicer(companyTpl, company);
    			var newcompanyhtml = option + companyhtml;
    			$(".companySelect").html(newcompanyhtml);
    		}
    	});
    };
	
	//添加根据机构类型获取公司
	function addgetCompany(organizationType) {
    	$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/organization/listByType',
    		dataType: 'json',
    		data: {
    			organizationType: organizationType
    		},
    		success: function(data) {
    			console.log(data);
    			var company = {};
    			company.list = data;
    			var companyTpl = document.getElementById("addcompanySelectTpl").innerHTML;
    			var companyhtml = juicer(companyTpl, company);
    			$(".addcompanySelect").html(companyhtml);
    		}
    	});
    }
	//编辑根据机构类型获取公司
	function editgetCompany(organizationType) {
    	$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/organization/listByType',
    		dataType: 'json',
    		data: {
    			organizationType: organizationType
    		},
    		success: function(data) {
    			console.log(data);
    			var company = {};
    			company.list = data;
    			var companyTpl = document.getElementById("editcompanySelectTpl").innerHTML;
    			var companyhtml = juicer(companyTpl, company);
    			$(".editcompanySelect").html(companyhtml);
    		}
    	});
    }
	
	//添加获取角色列表
	function getRoleList() {
		$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/role/roles',
    		dataType: 'json',
    		success: function(data) {
    			console.log(data);
    			var roles = {};
    			roles.list = data;
    			var roleTpl = document.getElementById("addroleSelectTpl").innerHTML;
    			var rolehtml = juicer(roleTpl, roles);
    			$(".addroleSelect").html(rolehtml);
    		}
    	});
	}
	
	//编辑获取角色列表
	function editgetRoleList() {
		$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/role/roles',
    		dataType: 'json',
    		success: function(data) {
    			console.log(data);
    			var roles = {};
    			roles.list = data;
    			var roleTpl = document.getElementById("editroleSelectTpl").innerHTML;
    			var rolehtml = juicer(roleTpl, roles);
    			$(".editroleSelect").html(rolehtml);
    		}
    	});
	}
	
	//状态启用与禁用
	function statusForbidOrNot(state, sysUserId) {
		$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/user/state',
    		dataType: 'json',
    		data: {
    			state: state,
    			sysUserId: sysUserId
    		},
    		success: function(data) {
    			console.log(data);
    			if(data == true) {
    				alert('修改成功');
    				location.replace(location.href);
    			}
    			else {
    				alert("修改失败");
    				
    			}
    		}
    	});
	}
	
	//确认添加用户
	function confirmadduser() {
		$('#adduserform').data('bootstrapValidator').validate();  
        if(!$('#adduserform').data('bootstrapValidator').isValid()){  
            return ;  
        }
        console.log(111222);
        var companyId = $(".addcompanySelect").find("option:selected").attr("value");//公司id
		var roleIds = $(".addroleSelect").find("option:selected").attr("value");//角色id
		var loginName = $(".addloginname").val();//登录名
		var password = $(".addpassword").val();//密码
		var phone = $(".addtelphone").val();//电话
		var remarks = $(".addbeizhu").val();//备注
		var trueName = $(".addtrueName").val();//真实姓名
		var userStatus = $(".addStatus").find("input:checked").attr("value");//登录状态0-否；1-可
		
		$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/user/add',
    		dataType: 'json',
    		data: {
    			companyId: companyId,
    			roleIds: roleIds,
    			loginName: loginName,
    			password: hex_md5(password),
    			phone: phone,
    			remarks: remarks,
    			trueName: trueName,
    			userStatus: userStatus
    		},
    		success: function(data) {
    			console.log(data);	
    			alert('添加成功');
    			location.replace(location.href);

    		},
    		error: function(data) {
    			alert(data.responseJSON.message);
    		}
    	});
        
	}
	//确认修改用户信息
	function saveuseredit() {
		$('#edituserform').data('bootstrapValidator').validate();  
        if(!$('#edituserform').data('bootstrapValidator').isValid()){  
            return ;  
        }
		var companyId = $(".editcompanySelect").find("option:selected").attr("value");//公司id
		var loginName = $(".editloginName input").val();//登录名
		var phone = $(".edittelphone").val();//电话
		var remarks = $(".editbeizhu").val();//备注
		var roleIds = $(".editroleSelect").find("option:selected").attr("value");//角色Id
		var trueName = $(".edittrueName input").val();//真实姓名
		var userStatus = $(".edituserStatus").find("input:checked").attr("value");
		$.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/user/update',
    		dataType: 'json',
    		data: {
    			companyId: companyId,
    			roleIds: roleIds,
    			loginName: loginName,
    			phone: phone,
    			remarks: remarks,
    			trueName: trueName,
    			userStatus: userStatus,
    			sysUserId: newsysUserId
    		},
    		success: function(data) {
    			console.log(data);	
    			alert('修改成功');
    			location.replace(location.href);

    		},
    		error: function(data) {
    			alert(data.responseJSON.message);
    		}
    	});
	}
	//确认修改密码
	function confirmeditpassword(newpassword) {
		$('#edituserpswform').data('bootstrapValidator').validate();  
        if(!$('#edituserpswform').data('bootstrapValidator').isValid()){  
            return ;  
        }
		$.ajax({
			type: 'POST',
			url: ctx+'/sys/v1/user/updatePwd',
			dataType: 'json',
			data: {
				newPwd: hex_md5(newpassword),
//				oldPwd: oldpassword,
				userId: newsysUserId
			},
			success: function(data) {
    			console.log(data);	
    			alert('修改成功');
    			location.replace(location.href);

    		},
    		error: function(data) {
    			alert(data.responseJSON.message);
    		}
		});
	}
	
	
});